﻿using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Coder.Workflow;
using Identity;

namespace Fee.Orders.FormalWorkflow
{
    public class FormalOrder : DelegateOrderBase
    {
        public const string FormalDelegateWorkflowName = "正式委托";
        public const string FormalDelegateStep1 = "委托管理员审核";

        private IList<FormalOrderPlanCost> _planCosts;
        public FormalOrder(WorkProcess wrWorkProcess, User user) : base(wrWorkProcess, user)
        {
        }

        protected FormalOrder()
        {
        }
        public IList<FormalOrderPlanCost> PlanCosts
        {
            get => _planCosts ?? (_planCosts = new List<FormalOrderPlanCost>());
            set => _planCosts = value;
        }

        public void UpdateBy(IEnumerable<FormalOrderPlanCost> dataPlanCosts)
        {
            var updateDate = dataPlanCosts.ToDictionary(
                f => f.Type,
                f => f
            );

            foreach (var item in PlanCosts)
                if (updateDate.ContainsKey(item.Type))
                    item.UpdateBy(updateDate[item.Type]);
        }
        public override void Complete()
        {
            base.Complete();

            foreach (var detail in this.Details)
            {
                if (detail.ContractType != ContractType.Design)
                {
                    var taskDetail = ConstructionTask.Details.FirstOrDefault(f =>
                          f.ContractType == detail.ContractType && f.ConstructionType == detail.ConstructionType);
                    if (taskDetail != null)
                    {
                        taskDetail.Status = ConstructionDetailStatus.Confirm;
                    }
                }
            }

            var result = ConstructionTask.PlanCosts.ToDictionary(f => f.Type, f => f);

            foreach (var orderPlanCost in PlanCosts)
            {
                ConstructionTaskPlanCost taskPlanCost = null;
                if (!result.ContainsKey(orderPlanCost.Type))
                {
                    taskPlanCost = new ConstructionTaskPlanCost
                    {
                        Type = orderPlanCost.Type,
                        ProcessInfo = { ConstructionOperator = ConstructionOperator.Added }
                    };
                }
                else
                {
                    taskPlanCost = result[orderPlanCost.Type];
                    taskPlanCost.ProcessInfo.ConstructionOperator = ConstructionOperator.Changed;
                }

                taskPlanCost.UpdateBy(orderPlanCost);
                taskPlanCost.ProcessInfo.Number = Number;

                ConstructionTask.PlanCosts.Add(taskPlanCost);
            }
        }
    }
}